<%
local brook_path = luci.sys.exec("echo -n `uci get brook_server.@global[0].brook_path`")
local brook_version = luci.sys.exec("[ -f '" .. brook_path .. "' ] && " .. brook_path .. " -v | awk '{print $3}'")
local dsp = require "luci.dispatcher"
-%>

<script type="text/javascript">
	//<![CDATA[
	var brookInfo;
	var tokenStr = '<%=token%>';
	var noUpdateText = '<%:已是最新版本%>';
	var updateSuccessText = '<%:更新成功.%>';
	var clickToUpdateText = '<%:点击更新%>';
	var inProgressText = '<%:正在更新...%>';
	var unexpectedErrorText = '<%:意外错误.%>';
	var updateInProgressNotice = '<%:正在更新，你确认要关闭吗？%>';

	window.onload = function() {
		var brookCheckBtn = document.getElementById('_brook-check_btn');
		var brookDetailElm = document.getElementById('_brook-check_btn-detail');
	};

	function addPageNotice_brook() {
		window.onbeforeunload = function(e) {
			e.returnValue = updateInProgressNotice;
			return updateInProgressNotice;
		};
	}

	function removePageNotice_brook() {
		window.onbeforeunload = undefined;
	}

	function onUpdateSuccess_brook(btn) {
		alert(updateSuccessText);

		if(btn) {
			btn.value = updateSuccessText;
			btn.placeholder = updateSuccessText;
			btn.disabled = true;
		}

		window.setTimeout(function() {
			window.location.reload();
		}, 1000);
	}

	function onRequestError_brook(btn, errorMessage) {
		btn.disabled = false;
		btn.value = btn.placeholder;

		if(errorMessage) {
			alert(errorMessage);
		}
	}

	function doAjaxGet(url, data, onResult) {
		new XHR().get(url, data, function(_, json) {
			var resultJson = json || {
				'code': 1,
				'error': unexpectedErrorText
			};

			if(typeof onResult === 'function') {
				onResult(resultJson);
			}
		})
	}

	function onBtnClick_brook(btn) {
		if(brookInfo === undefined) {
			checkUpdate_brook(btn);
		} else {
			doUpdate_brook(btn);
		}
	}

	function checkUpdate_brook(btn) {
		btn.disabled = true;
		btn.value = inProgressText;

		addPageNotice_brook();

		var ckeckDetailElm = document.getElementById(btn.id + '-detail');

		doAjaxGet('<%=dsp.build_url("admin/vpn/brook_server/check")%>', {
			token: tokenStr,
			arch: ''
		}, function(json) {
			removePageNotice_brook();

			if(json.code) {
				brookInfo = undefined;
				onRequestError_brook(btn, json.error);
			} else {
				if(json.update) {
					brookInfo = json;
					btn.disabled = false;
					btn.value = clickToUpdateText;
					btn.placeholder = clickToUpdateText;
					
					if(ckeckDetailElm) {
						var urlNode = '';
						if(json.version) {
							urlNode = '<em style="color:red;">最新版本号：' + json.version + '</em>';
							if(json.url && json.url.html) {
								urlNode = '<a href="' + json.url.html + '" target="_blank">' + urlNode + '</a>';
							}
						}
					ckeckDetailElm.innerHTML = urlNode;
					}
				} else {
					btn.disabled = true;
					btn.value = noUpdateText;
				}
			}
		});
	}

	function doUpdate_brook(btn) {
		btn.disabled = true;
		btn.value = '<%:下载中...%>';

		addPageNotice_brook();

		var brookUpdateUrl = '<%=dsp.build_url("admin/vpn/brook_server/update")%>';
		// Download file
		doAjaxGet(brookUpdateUrl, {
			token: tokenStr,
			url: brookInfo ? brookInfo.url.download : ''
		}, function(json) {
			if(json.code) {
				removePageNotice_brook();
				onRequestError_brook(btn, json.error);
			} else {
				btn.value = '<%:解压中...%>';
				
				// Move file to target dir
				doAjaxGet(brookUpdateUrl, {
					token: tokenStr,
					task: 'move',
					file: json.file
				}, function(json) {
					removePageNotice_brook();
					if(json.code) {
						onRequestError_brook(btn, json.error);
					} else {
						onUpdateSuccess_brook(btn);
					}
				})
			}
		})
	}
	//]]>
</script>

<div class="cbi-value">
	<label class="cbi-value-title">Brook
		<%:Version%>
	</label>
	<div class="cbi-value-field">
		<div class="cbi-value-description">
			<span>【 <%=brook_version%>】</span>
			<input class="cbi-button cbi-input-apply" type="submit" id="_brook-check_btn" onclick="onBtnClick_brook(this);" value="<%:Manually update%>">
			<span id="_brook-check_btn-detail"></span>
		</div>
	</div>
</div>